'use strict';
const dayjs = require("dayjs");

module.exports = app => {
    const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;
    const OrderItem =  app.model.define(
        'OrderItem',
        {
            id: {type: INTEGER, primaryKey: true, autoIncrement: true},
            order_id: INTEGER,
            order_no: STRING(255),
            user_id: INTEGER,
            product_id: INTEGER,
            count: {type: INTEGER, defaultValue: 0},
            product_detail: TEXT,
            create_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            update_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            }
        },
        {
            tableName: 'order_item',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );
    OrderItem.associate = function () {
        // 关联
        app.model.OrderItem.belongsTo(app.model.Order, {as: 'order', foreignKey: 'order_id'});
        app.model.OrderItem.belongsTo(app.model.Product, {as: 'product', foreignKey: 'product_id'});
        app.model.OrderItem.belongsTo(app.model.User, {as: 'user', foreignKey: 'user_id'});
    }
    return OrderItem
};
// 创建mysql表，需要有注释
// CREATE TABLE `order_item` (
//     `id` int NOT NULL AUTO_INCREMENT,
//     `order_id` int DEFAULT NULL COMMENT '订单id',
//     `order_no` varchar(255) DEFAULT NULL COMMENT '订单号',
//     `user_id` int DEFAULT NULL COMMENT '用户id',
//     `product_id` int DEFAULT NULL COMMENT '产品id',
//     `product_detail` text COMMENT '产品详情',
//     `create_time` datetime DEFAULT NULL COMMENT '创建时间',
//     `update_time` datetime DEFAULT NULL COMMENT '更新时间',
//     PRIMARY KEY (`id`) USING BTREE
// ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='订单项';
